package com.vr.xuecheng.base.handler;

import com.vr.xuecheng.base.exception.XueChengPlusException;
import com.vr.xuecheng.base.exception.enums.CommonErrorEnum;
import com.vr.xuecheng.base.response.RestErrorResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.ArrayList;

/**
 * @author hzh
 * @date 2025/03/04
 * 全局异常处理类
 */
@Slf4j
@Configuration
@RestControllerAdvice
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public class GlobalExceptionHandler {


    /**
     * @param e 异常对象
     * @return {@code RestErrorResponse }
     * 自定义异常处理
     */
    @ExceptionHandler
    public RestErrorResponse xueChengPlusExceptionHandler(XueChengPlusException e) {
        log.error("type:{}catch,exception:{}",e.getClass(),e.getMessage());
        return new RestErrorResponse(e.getMessage());
    }

    /**
     * @param e 异常对象
     * @return {@code RestErrorResponse }
     * 校验异常
     */
    @ExceptionHandler
    public RestErrorResponse methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        log.error("type:{}catch,exception:{}",e.getClass(),e.getMessage());
        BindingResult bindingResult = e.getBindingResult();
        StringBuffer errMessage = new StringBuffer();

        bindingResult.getFieldErrors().forEach(error -> {
            errMessage.append(error.getDefaultMessage()).append(",");
        });
        errMessage.deleteCharAt(errMessage.length()-1);
        return new RestErrorResponse(errMessage.toString());
    }

    /**
     * @param e 异常对象
     * @return {@code RestErrorResponse } 结果
     * 兜底方案
     */
    @ExceptionHandler
    public RestErrorResponse exceptionHandler(Exception e) {
        log.error("type:{}catch,exception:{}",e.getClass(),e.getMessage());
        return new RestErrorResponse(CommonErrorEnum.UNKNOWN_ERROR.getErrorMessage());
    }
}
